// 1. 导入express
import express from "express";
import { expressjwt } from 'express-jwt'
import { port, host, jwtSecretKey } from './server.config';
import selectTable from "./routes/selectTable";
import login from "./routes/login";
import user from "./routes/user";
import reward from "./routes/reward";
import bonus from "./routes/bonus";
import todo from "./routes/todo";
const { json, urlencoded } = express;
// 2. 创建express实例
const app = express();
// 3. 处理跨域
app.all("*", (req: { method: string; }, res: { header: (arg0: string, arg1: string) => void; send: (arg0: number) => void; }, next: () => void) => {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "content-type");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == "options") {
    res.send(200); // 让options尝试请求快速结束
  } else {
    next();
  }
});
// 4. 监听
app.listen(port, "0.0.0.0");

// 5. 处理中间件设置body解析中间件
app.use(json());
app.use(urlencoded({ extended: true }));
app.use(expressjwt({ secret: jwtSecretKey, algorithms: ["HS256"] }).unless({ path: ['/login', /^\/img/, /^\/uploads/] }))
// 6. 处理路由
app.use("/login", login);
app.use("/user", user);
app.use("/selectTable", selectTable);
app.use("/reward", reward);
app.use("/bonus", bonus);
app.use("/todo", todo);
// 7. 处理静态资源
app.use(express.static("public"))
app.use(function (err: any, req: any, res: any, next: any) {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("invalid token...");
  } else {
    next(err);
  }
});

// 8. 打印输出提示信息
console.log(`server running at http://${host}:${port}`);
